package web.controller.common;

import common.consts.Consts;
import common.consts.ContentType;
import common.validation.ValidationResult;
import domain.Education;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import service.ServiceResponse;
import service.UserProfileService;
import web.Routes;
import web.controller.Base;
import web.req.UserProfileRequest;
import web.security.Protection;

/**
 * Created by liuchang on 2015/6/27.
 */
@RestController
@RequestMapping(Routes.Common.PROFILE)
public class UserProfile extends Base {

    private static final Logger logger = LoggerFactory.getLogger(UserProfile.class);

    @Autowired
    private UserProfileService userProfileService;

    @Protection
    @RequestMapping(method = RequestMethod.POST, produces = ContentType.JSON)
    public ServiceResponse save(@RequestBody UserProfileRequest request) {
        ValidationResult result = request.validate();
        if (!result.isSuccess()) {
            return fail(result.getMessage());
        }
        long id = getUserIdFromAuthHeader();
        request.setId(id);

        domain.UserProfile userProfile = new domain.UserProfile();
        Education education = new Education();
        try {
            BeanUtils.copyProperties(request, userProfile);
            BeanUtils.copyProperties(request, education);
        } catch (Exception e) {
            logger.warn("bean(userProfile) properties copy failed.", e);
            return fail(Consts.i18nKey.SYSTEM_ERROR);
        }

        return userProfileService.updateProfileAndEducation(userProfile, education);
    }

    @Protection
    @RequestMapping(method = RequestMethod.GET, produces = ContentType.JSON)
    public ServiceResponse get() {
        long user = getUserIdFromAuthHeader();
        ServiceResponse response = userProfileService.getMyCompleteProfile(user);
        return response;
    }


}
